import logging
from channels.generic.websocket import AsyncWebsocketConsumer
import json

from videocall import settings

logger = logging.getLogger("django")


class RoomConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # station_sn = self.scope['url_route']['kwargs']['station_sn']
        # point_code = self.scope['url_route']['kwargs']['point_code']
        self.room_group_name = settings.GROUP_NAME
        # # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data=None, bytes_data=None):

        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat.message',
                "message": text_data,
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        message = event["message"]
        print("chat_message: {}, {}".format(type(message), message))
        await self.send(text_data=json.dumps({
            'message': message
        }))

